package com.mall.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.dao.AttrGroupDao;
import com.mall.entity.*;
import com.mall.service.*;
import com.mall.vo.AttrGroupWithAttrsVo;
import com.mall.vo.AttrsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.Query;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroup> implements AttrGroupService {

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;


    @Override
    public IPage<AttrGroup> queryPage(Long catelogId, Map<String, String> map) {

        Integer currentPage = Integer.valueOf(map.get("page"));
        Integer pageSize = Integer.valueOf(map.get("limit"));
        IPage<AttrGroup> attrGroupIPage;

        if (catelogId == 0){
            List<AttrGroup> attrGroups = attrGroupDao.selectList(null);
            attrGroupIPage = listToPage(attrGroups, currentPage, pageSize);
        }else {
                String key = map.get("key");
                QueryWrapper<AttrGroup> wrapper = new QueryWrapper<AttrGroup>().eq("category_id",catelogId);
                if (!StringUtils.isEmpty(key)){
                    wrapper.and((obj)->{
                        obj.eq("attr_group_id",key).or().like("attr_group_name",key);
                    });
                }
                List<AttrGroup> attrGroups = attrGroupDao.selectList(wrapper);
//                System.out.println(attrGroups);
                attrGroupIPage = listToPage(attrGroups, currentPage, pageSize);
        }
        return attrGroupIPage;
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        //1、查询分组信息
        List<AttrGroup> attrGroupEntities = this.list(new QueryWrapper<AttrGroup>().eq("category_id", catelogId));

        //2、查询所有属性
        List<AttrGroupWithAttrsVo> collect = attrGroupEntities.stream().map(group -> {
            AttrGroupWithAttrsVo attrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(group,attrsVo);
            List<Attr> attrs = attrService.getRelationAttr(attrsVo.getAttrGroupId());
            attrsVo.setAttrs(attrs);
            return attrsVo;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public void saveAllAttr(String groupName, Long id, AttrsVo[] attrsVos) {
        List<SpuInfo> list = spuInfoService.list(new QueryWrapper<SpuInfo>().eq("id", id));
        Long catId = null;
        //Long attrId=null;
        Long attrGroupId=null;
        //先根据id查找cat_id 在spu_info
        for (SpuInfo spuInfo : list) {
            AttrGroup attrGroup = new AttrGroup();
            attrGroup.setAttrGroupName(groupName);
            attrGroup.setCategoryId(spuInfo.getCatId());
            attrGroup.setSort(0);
            attrGroup.setDescript(groupName);
            attrGroupDao.insert(attrGroup);
            catId = spuInfo.getCatId();
            attrGroupId = attrGroup.getAttrGroupId();
        }
        // 设置分组名称 xy_attr_group
//        String values = "";
        ArrayList<ProductAttrValue> productAttrValues = new ArrayList<>();

        for (AttrsVo attrsVo : attrsVos) {
            String key = attrsVo.getKey();
            String value = attrsVo.getValue();
//            values = values + "" + value +";";
            com.mall.entity.Attr attrs = new Attr();
            attrs.setAttrName(key);
            attrs.setValueSelect(value);
            attrs.setStatus(1L);
            attrs.setAttrType(1);
            attrs.setCategoryId(catId);
            attrs.setShowDesc(1);
            attrs.setSearchType(1);
            attrs.setValueType(1);
            attrService.save(attrs);


            Long attrId = attrs.getAttrId();
            ProductAttrValue productAttrValue = new ProductAttrValue();
            productAttrValue.setAttrName(key);
            productAttrValue.setAttrValue(value);
            productAttrValue.setSpuId(id);
            productAttrValue.setAttrSort(0);
            productAttrValue.setAttrId(attrId);
            productAttrValue.setQuickShow(0);
            productAttrValues.add(productAttrValue);


            AttrAttrgroupRelation relation = new AttrAttrgroupRelation();
            relation.setAttrId(attrId);
            relation.setAttrGroupId(attrGroupId);
            attrAttrgroupRelationService.save(relation);
        }

        productAttrValueService.saveProductAttr(productAttrValues);
        //设置属性
        //设置属性值 spu_id attr_id
    }


    /**
     * 转化为ipage的方法
     */
    public static IPage<AttrGroup> listToPage(List<AttrGroup> list, int pageNum, int pageSize){
        List<AttrGroup> pageList = new ArrayList<>();
        int curIdx = pageNum > 1 ? (pageNum - 1) * pageSize : 0;
        for (int i = 0; i < pageSize && curIdx + i < list.size(); i++) {
            pageList.add(list.get(curIdx + i));
        }
        IPage<AttrGroup> page = new Page<>(pageNum, pageSize);
        page.setRecords(pageList);
        page.setTotal(list.size());
        return page;
    }

}